<template>
    <div class="login">
        <div class="left-wrap">
            <LoginLeftView></LoginLeftView>
        </div>
        <div class="right-wrap">
            <div class="top-right-wrap">
                <div class="btn theme-btn" @click="toggleTheme">
                    <i class="iconfont-sys">
                        {{ isDark ? '&#xe6b5;' : '&#xe725;' }}
                    </i>
                </div>
                <el-dropdown @command="changeLanguage" popper-class="langDropDownStyle">
                    <div class="btn language-btn">
                        <i class="iconfont-sys icon-language">&#xe611;</i>
                    </div>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <div v-for="lang in languageOptions" :key="lang.value" class="lang-btn-item">
                                <el-dropdown-item
                                    :command="lang.value"
                                    :class="{ 'is-selected': locale === lang.value }"
                                >
                                    <span class="menu-txt">{{ lang.label }}</span>
                                    <i v-if="locale === lang.value" class="iconfont-sys icon-check">&#xe621;</i>
                                </el-dropdown-item>
                            </div>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
            <div class="header">
                <ArtLogo class="icon" />
                <h1>{{ systemName }}</h1>
            </div>
            <div class="login-wrap">
                <div class="form">
                    <h3 class="title">{{ $t('login.title') }}</h3>
                    <p class="sub-title">{{ $t('login.subTitle') }}</p>
                    <el-form
                        ref="formRef"
                        :model="loginForm"
                        :rules="rules"
                        @keyup.enter="handleLogin"
                        style="margin-top: 25px"
                    >
                        <el-form-item prop="account">
                            <el-select v-model="loginForm.tenantId">
                                <el-option
                                    v-for="tenant in tenantList"
                                    :key="tenant.tenantId"
                                    :label="tenant.companyName"
                                    :value="tenant.tenantId"
                                >
                                    <span>{{ tenant.companyName }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="username">
                            <el-input
                                :placeholder="$t('login.placeholder[0]')"
                                v-model.trim="loginForm.username"
                            />
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input
                                :placeholder="$t('login.placeholder[1]')"
                                v-model.trim="loginForm.password"
                                type="password"
                                radius="8px"
                                autocomplete="off"
                            />
                        </el-form-item>
                        <el-form-item v-if="true" prop="code">
                            <el-input
                                v-model="loginForm.code"
                                size="large"
                                auto-complete="off"
                                :placeholder="$t('login.code')"
                                style="width: 50%;margin-right: 32px"
                                @keyup.enter="handleLogin"
                            >
                                <template #prefix>
                                    <svg-icon icon-class="validCode" class="el-input__icon input-icon" />
                                </template>
                            </el-input>
                            <div class="login-code">
                                <img :src="codeUrl" class="login-code-img" @click="getCode" />
                            </div>
                        </el-form-item>
                        <div class="forget-password">
                            <el-checkbox v-model="loginForm.rememberMe">{{
                                    $t('login.rememberPwd')
                                }}
                            </el-checkbox>
                            <router-link to="/forget-password">{{ $t('login.forgetPwd') }}</router-link>
                        </div>

                        <div style="margin-top: 30px">
                            <el-button
                                class="login-btn"
                                type="primary"
                                @click="handleLogin"
                                :loading="loading"
                                v-ripple
                            >
                                {{ $t('login.btnText') }}
                            </el-button>
                        </div>

                        <div class="footer">
                            <p>
                                {{ $t('login.noAccount') }}
                                <router-link to="/register">{{ $t('login.register') }}</router-link>
                            </p>
                        </div>
                    </el-form>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
    // 切换语言
    import { languageOptions } from '@/hooks/language'
    import { LanguageEnum, SystemThemeEnum } from '@/service/enums/appEnum'
    import { useI18n } from 'vue-i18n'

    const { t,locale } = useI18n()

    const changeLanguage = (lang: LanguageEnum) => {
        if (locale.value === lang) return
        locale.value = lang
        userStore.setLanguage(lang)
    }
    import AppConfig from '@/hooks/config'

    const systemName = AppConfig.systemInfo.name

    onMounted(() => {
        getCode()
        initTenantList()
        getLoginData()
    })

    /**
     * 切换主题
     */
    import { useSettingStore } from '@/service/store/modules/setting'

    const settingStore = useSettingStore()
    const { isDark, systemThemeType } = storeToRefs(settingStore)
    import { useTheme } from '@/hooks/useTheme'

    const toggleTheme = () => {
        let { LIGHT, DARK } = SystemThemeEnum
        useTheme().switchThemeStyles(systemThemeType.value === LIGHT ? DARK : LIGHT)
    }
    // 用户登录
    import { formRef, loginForm, rules } from './AccountService'

    import { useUserStore } from '@/service/store/modules/user'
    import { TenantVO, LoginService, LoginData } from '@/service/LoginService'
    import { HOME_PAGE } from '@/router/routesAlias'

    const userStore = useUserStore()
    const router = useRouter()

    const loading = ref(false)

    const getLoginData = () => {
        const tenantId = localStorage.getItem('tenantId')
        const username = localStorage.getItem('username')
        const password = localStorage.getItem('password')
        const rememberMe = localStorage.getItem('rememberMe')
        loginForm.value = {
            tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
            username: username === null ? String(loginForm.value.username) : username,
            password: password === null ? String(loginForm.value.password) : String(password),
            rememberMe: rememberMe === null ? false : Boolean(rememberMe)
        } as LoginData
    }
    /**
     * 获取租户列表
     */
    const tenantEnabled = ref(true)
    const tenantList = ref<TenantVO[]>([])
    const initTenantList = async () => {
        const { data } = await LoginService.getTenantList(false)
        tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled
        if (tenantEnabled.value) {
            tenantList.value = data.voList
            if (tenantList.value != null && tenantList.value.length !== 0) {
                loginForm.value.tenantId = tenantList.value[0].tenantId
            }
        }
    }

    /**
     * 获取验证码
     */
    const codeUrl = ref('')
    const captchaEnabled = ref(true)
    const getCode = async () => {
        const res = await LoginService.getCodeImg()
        const { data } = res
        captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled
        if (captchaEnabled.value) {
            codeUrl.value = 'data:image/gif;base64,' + data.img
            loginForm.value.uuid = data.uuid
        }
    }
    const handleLogin = async () => {
        loading.value = true
        // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
        if (loginForm.value.rememberMe) {
            localStorage.setItem('tenantId', String(loginForm.value.tenantId))
            localStorage.setItem('username', String(loginForm.value.username))
            localStorage.setItem('password', String(loginForm.value.password))
            localStorage.setItem('rememberMe', String(loginForm.value.rememberMe))
        } else {
            // 否则移除
            localStorage.removeItem('tenantId')
            localStorage.removeItem('username')
            localStorage.removeItem('password')
            localStorage.removeItem('rememberMe')
        }
        const { data } = await LoginService.login(loginForm.value)
        if (data != null) {
            userStore.setToken('Bearer ' + data.access_token)
            const res = await LoginService.getInfo()
            // 设置登录状态
            userStore.setLoginStatus(true)
            // 登录成功提示
            showLoginSuccessNotice()
            debugger
            if (res.code === 200) {
                userStore.setUserInfo(res.data)
                userStore.setLoginStatus(true)
                router.push(HOME_PAGE)
            } else {
                ElMessage.error(res.msg)
            }
            loading.value = false
        } else {
            loading.value = false
            // 重新获取验证码
            if (captchaEnabled.value) {
                await getCode()
            }
        }
    }
    // 登录成功提示
    const showLoginSuccessNotice = () => {
        setTimeout(() => {
            ElNotification({
                title: t('login.success.title'),
                type: 'success',
                duration: 2500,
                zIndex: 10000,
                message: `${t('login.success.message')}, ${userStore.getUserInfo.user?.nickName}!`
            })
        }, 150)
    }
</script>

<style lang="scss" scoped>
    @use 'index';
</style>
